package cn.enine.tbcharge.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import cn.enine.tbcharge.R;
import cn.enine.tbcharge.base.MyBaseActivity;
import cn.enine.tbcharge.pojo.AppSfMain;
import cn.enine.tbcharge.pojo.AppSfSub;
import cn.enine.tbcharge.pojo.AppXmpy;
import cn.enine.tbcharge.pojo.RetMsg;
import cn.enine.tbcharge.util.HttpUrl;
import cn.enine.tbcharge.util.MyToastUtil;
import cn.enine.tbcharge.util.NetWorkUtils;
import cn.enine.tbcharge.util.SharedPreferencesUtils;
import cn.enine.tbcharge.util.StringUtils;
import cn.enine.tbcharge.util.UplodeManager;
import cn.enine.tbcharge.util.UserClient;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import org.litepal.LitePal;

/**
 * 用户登录
 *
 * @author
 */
public class LoginActivity extends MyBaseActivity {
    Button login;//登录按钮
    EditText username, password;
    CheckBox jzmm;
    Context con = LoginActivity.this;
    ZLoadingDialog dialog;
    int jmcount = 0;//居民
    int signcount=0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        initUI();
        initData();
        initListener();
    }

    @Override
    protected void initUI() {
        // TODO Auto-generated method stub
        setContentView(R.layout.activity_login);
        login = (Button) findViewById(R.id.login);
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        username.setText(SharedPreferencesUtils.getParam(con, "username", "").toString());
        password.setText(SharedPreferencesUtils.getParam(con, "password", "").toString());
        jzmm = (CheckBox) findViewById(R.id.jzmm);
        username.setText(SharedPreferencesUtils.getParam(con, "username", "").toString());
        password.setText(SharedPreferencesUtils.getParam(con, "password", "").toString());
        dialog = new ZLoadingDialog(con);
        dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
                .setLoadingColor(Color.parseColor("#1C86EE"))//颜色
                .setHintText("Loading...")
                .setHintTextSize(16) // 设置字体大小 dp
                .setHintTextColor(Color.parseColor("#1C86EE"));  // 设置字体颜色
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        // TODO Auto-generated method stub
        login.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetWorkUtils.isNetworkConnected(con)) {
                    //网络可以使用
                    signcount=0;
                    jmcount=0;
                    RequestParams ps = new RequestParams();
                    ps.add("username", username.getText().toString());
                    ps.add("password", password.getText().toString());
                    ps.add("type", "2");
                    UserClient.get(HttpUrl.User_Login, ps, new AsyncHttpResponseHandler() {
                        @Override
                        public void onStart() {
                            super.onStart();
                            dialog.show();
                        }
                        @Override
                        public void onFailure(int statusCode, Throwable error, String content) {
                            super.onFailure(statusCode, error, content);
                            dialog.dismiss();
                            if (SharedPreferencesUtils.getParam(con, "username", "").toString().equals(username.getText().toString()) &&
                                    SharedPreferencesUtils.getParam(con, "password", "").toString().equals(password.getText().toString())) {
                                MyToastUtil.ShowToast(con, "登录成功");
                                startActivity(new Intent(con, MainActivity.class));
                                finish();
                            } else {
                                dialog.dismiss();
                                MyToastUtil.ShowToast(con, "登录失败");
                            }
                        }
                        @Override
                        public void onSuccess(int statusCode, String content) {
                            super.onSuccess(statusCode, content);
                            Log.i("登录成功",content);
                            RetMsg ret = JSON.parseObject(content, RetMsg.class);
                            JSONObject j = JSON.parseObject(ret.getRd());
                            if (ret.getCode().equals("5001")) {
                                dialog.dismiss();
                                MyToastUtil.ShowToast(con, "用户名或密码错误");
                            }else if (ret.getCode().equals("200")) {
                                MyToastUtil.ShowToast(con, "登录成功");
                                if (jzmm.isChecked()) {
                                    SharedPreferencesUtils.setParam(con, "username", username.getText().toString());
                                    SharedPreferencesUtils.setParam(con, "password", password.getText().toString());
                                } else {
                                    SharedPreferencesUtils.setParam(con, "username", "");
                                    SharedPreferencesUtils.setParam(con, "password", "");
                                }
                                SharedPreferencesUtils.setParam(con, "uid", username.getText().toString());
                                SharedPreferencesUtils.setParam(con, "token", j.getString("_token"));
                                SharedPreferencesUtils.setParam(con, "uname", StringUtils.isEmpty(j.getString("name"))?"":j.getString("name"));
                                SharedPreferencesUtils.setParam(con, "phone",StringUtils.isEmpty(j.getString("phone"))?"":j.getString("phone"));
                                SharedPreferencesUtils.setParam(con, "yljg", StringUtils.isEmpty(j.getString("yljg"))?"":j.getString("yljg"));
                                SharedPreferencesUtils.setParam(con, "rybh",StringUtils.isEmpty(j.getString("rybh"))?"":j.getString("rybh"));
                                SharedPreferencesUtils.setParam(con, "isgly",StringUtils.isEmpty(j.getString("isgly"))?"":j.getString("isgly"));
                                SharedPreferencesUtils.setParam(con, "yljgname", StringUtils.isEmpty(j.getString("yljgname"))?"":j.getString("yljgname"));
                                getXm();
                            }
                        }
                    });
                } else {//网络不能使用，也能进入，但是首次不行
                    if (SharedPreferencesUtils.getParam(con, "username", "").toString().equals(username.getText().toString()) &&
                            SharedPreferencesUtils.getParam(con, "password", "").toString().equals(password.getText().toString())) {
                        MyToastUtil.ShowToast(con, "登录成功");
                        startActivity(new Intent(con, MainActivity.class));
                        finish();
                    } else {
                        dialog.dismiss();
                        MyToastUtil.ShowToast(con, "登录失败");
                    }
                }
            }
        });
    }

    public void getXm() {
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("isupdate", "1");
        UserClient.get(HttpUrl.GetXmAll, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
                dialog.show();
            }

            @Override
            public void onFailure(int statusCode, Throwable error, String content) {
                super.onFailure(statusCode, error, content);
                dialog.dismiss();
                MyToastUtil.ShowToast(con, "请求失败");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                dialog.dismiss();
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {
                    List<AppXmpy> appXmpyList = JSON.parseArray(ret.getRd(), AppXmpy.class);
                    JSONArray js = JSON.parseArray(ret.getRd());
                    for (int i = 0; i < js.size(); i++) {
                        JSONObject j = js.getJSONObject(i);
                    }
                    for (int i = 0; i < appXmpyList.size(); i++) {
                        AppXmpy fwqAppXmpy = appXmpyList.get(i);
                        List<AppXmpy> bdList = LitePal.where("nid = ?", fwqAppXmpy.getNid()).find(AppXmpy.class);
                        if (null !=bdList && bdList.size() > 0) {
                            //本地已存在
                            if(fwqAppXmpy.getIsupdate()==1) {//需要更新
                                bdList.get(0).delete();
                                appXmpyList.get(i).save();
                            }
                        } else {
                            //本地不存在
                            appXmpyList.get(i).save();
                        }
                    }
                } else {
                    dialog.dismiss();
                    MyToastUtil.ShowToast(con, "收费项目信息获取错误");
                }
                isupdate();
            }
        });
    }

    //判断是否需需要进行更新
    public void isupdate(){
        RequestParams ps=new RequestParams();
        ps.add("token",SharedPreferencesUtils.getParam(con,"token","").toString());
        ps.add("type","2");
        ps.add("version","1.0.1");
        UserClient.get(HttpUrl.IsUpdate,ps,new AsyncHttpResponseHandler(){
            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                RetMsg ret= JSON.parseObject(content,RetMsg.class);

                if(ret.getCode().equals("200")){
                    UplodeManager mUpdateManager = new UplodeManager(con, ret.getRd());
                    mUpdateManager.checkUpdateInfo();
                }else{
                    startActivity(new Intent(con, MainActivity.class));
                    finish();
                }
            }
        });
    }
}
